package org.person.gift.rocketmq.listener;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.peron.gift.clients.OrderClient;
import org.person.gift.constants.OrderConstant;
import org.person.gift.domain.OrderGift;
import org.person.gift.domain.PayOrder;
import org.person.gift.dto.PlaceOrderDTO;
import org.person.gift.service.IPayOrderService;
import org.person.gift.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @Auther Stark
 * @Date 2024/02/24
 */
@Component
@RocketMQMessageListener(topic = OrderConstant.PLACE_ORDER_TX_TOPIC,
        consumerGroup = OrderConstant.PLACE_ORDER_TX_PAY_CONSUMER_GROUP)
public class PayOrderMessageListener implements RocketMQListener<MessageExt> {

    @Autowired
    private IPayOrderService payOrderService;

    @Autowired
    private OrderClient orderClient;

    @Override
    public void onMessage(MessageExt messageExt) {
        // 获取消息
        byte[] body = messageExt.getBody();
        String s = new String(body);
        PlaceOrderDTO dto = JSONObject.parseObject(s, PlaceOrderDTO.class);
        // 根据父订单编号查询支付单的信息,如果能查询到说明已经创建过支付单,那就跳过
        List<PayOrder> payOrderList = payOrderService.selectList(new EntityWrapper<PayOrder>().eq("business_id", dto.getParentOrderNo()));
        // rocketmq在消费时,抛出异常信息时会重试
        if(payOrderList == null || payOrderList.size() == 0) {
            // 创建支付单
            PayOrder payOrder = new PayOrder();
            payOrder.setCreateTime(new Date());
            // 发生金额 = 订单的总金额  调用订单服务查询
            AjaxResult ajaxResult = orderClient.getOrderByParentOrderNo(dto.getParentOrderNo().toString());
            if (!ajaxResult.isSuccess()) {
                throw new RuntimeException("创建支付单失败!");
            }
            String jsonString = JSONObject.toJSONString(ajaxResult.getResultObj());
            List<OrderGift> orderGifts = JSONArray.parseArray(jsonString, OrderGift.class);
            BigDecimal amount = orderGifts.stream().map(OrderGift::getTotalAmount).reduce(BigDecimal::add)
                    .orElse(BigDecimal.ZERO);
            payOrder.setAmount(amount);

            payOrder.setPayType(dto.getPayType());
            // 充值订单的下单接口和礼物订单不是同一个,到时候如果有充值订单,支付服务要额外的做处理
            payOrder.setBusinessType(0);
            payOrder.setBusinessId(dto.getParentOrderNo());
            payOrder.setUserId(dto.getUserId());
            payOrder.setPayStatus(0);
            payOrder.setUniPayOrderSn(dto.getUnionPayOrderSn());
            payOrderService.insert(payOrder);
        }
    }
}
